<?php


namespace app\common\behavior;


use app\common\library\wechat\WxClient;
use app\common\model\User;
use app\common\model\WxAppMsg;
use think\Log;

class WxMessage
{
    public function afterPay($order)
    {
        try {
            $wxClient = new WxClient();
            $orderGoods = $order->goods;
            $products = [];
            $goodsCount = 0;
            foreach ($orderGoods as $orderGood) {
                $products[] = $orderGood->goods_name;
                $goodsCount += $orderGood->total_num;
            }
            $data = [
                'thing1' => ['value' => implode(",", $products)],
                'amount2' => ['value' => $order->pay_price],
                'number3' => ['value' => $goodsCount],
                'time4' => ['value' => date('Y-m-d H:i:s')],
                'character_string6' => ['value' => $order->order_no]
            ];
            $userInfo = User::get($order->user_id);
            $openId = $userInfo->open_id;
            $template_id = "_gbU4La87TZuPSWqkZIZ7Qkht8XpDSLxPWf86F3-FbE";
            $page = "/pages/order/detail?order_id=" . $order->order_id;
            $wxClient->sendMessage($data, $openId, $template_id, $page);
        } catch (\Exception $e) {
            Log::record("发送微信通知时异常：" . $e->getMessage());
        }
    }


    public function afterCommission($data)
    {
        try {
            $commissionLog = $data['commissionLog'];
            $user = $data['user'];
            $orderCreator = $data['orderCreator'];
            Log::record("余额变动提醒");
            $template_id = "vmEFBaRcFyMK42ZmaK64u5Ou7QbAlTO45GxvB0YE4jw";
            $content = "{$orderCreator->nickName} 购买了 {$commissionLog->goods_name} 获得分润";
            $data = [
                'amount1' => ['value' => $commissionLog->money],
                'amount2' => ['value' => $user->balance],
                'time3' => ['value' => date('Y-m-d H:i:s')],
                'thing4' => ['value' => $content],
                'thing5' => ['value' => '']
            ];
            $page = "/pages/agent/order/detail?order_id=" . $commissionLog->relate_id;
            $wxappMsgModel = new WxAppMsg();
            $wxappMsgModel->addMsg($commissionLog->relate_id, $data, $user->open_id, $template_id, $page);
//            $wxClient = new WxClient();
//            $wxClient->sendMessage($data, $user->open_id, $template_id, $page);
        } catch (\Exception $e) {
            Log::record("发送余额变更提醒时发生异常：" . $e->getMessage());
        }
    }
}
